package com.yanqu.road.server.timer.activity;

import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.exchange.ExchangeModule;
import com.yanqu.road.server.manger.ForbiddenIpMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.executor.GeneralTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ActivityReloadTask extends GeneralTask {

    private Logger logger = LogManager.getLogger(this.getClass().getName());

    private long lastLoadTime = LocalDateTimeHelper.getZeroTimeTimeStamp();

    private boolean isRun = false;

    private static long lastReloadForbiddenTime = System.currentTimeMillis();

    private long lastReloadTime = System.currentTimeMillis();

    @Override
    public void doRun() {
        //每天重新加载活动
        long now = System.currentTimeMillis();
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp();
        long nextZeroTime = zeroTime + 3600L * 1000 * 24;
        if (nextZeroTime - now < 60 * 1000L && lastReloadTime < nextZeroTime ) {
            //59分要加载一次
            ActivityMgr.reloadAllActivityInfoInMemory();
            lastReloadTime = nextZeroTime;
        }
        if (lastLoadTime < zeroTime && !isRun) {
            isRun = true;
            try {
                ActivityMgr.taskReload();
                lastLoadTime = zeroTime;
            } catch (Exception e) {
                logger.error("reload activity error:", e);
            } finally {
                isRun = false;
            }
        }

        try {
            for (GamePlayer player : GamePlayerMgr.getCopyPlayerMap().values()) {
                player.getModule(ExchangeModule.class).lazyLoad();
            }
        } catch (Exception ex) {

        }

        long nowTime = System.currentTimeMillis();
        if (nowTime - zeroTime >= 5) {
            LogMgr.saveServerDb();
            long costTime = System.currentTimeMillis() - nowTime;
            if (costTime >= 20) {
                logger.info("save serveDb cost {} millSeconds.", costTime);
            }
        }

        // 重新加载IP 0点前后一分钟内不执行
        if (((nowTime - zeroTime) <= 10 * 60 * 1000) || ((24 * 60 * 60 * 1000 - nowTime + zeroTime) <= 10 * 60 * 1000)) {
            return;
        }
        if (nowTime - lastReloadForbiddenTime >= 60 * 1000) {
            ForbiddenIpMgr.reloadForbiddenIp();
            lastReloadForbiddenTime = nowTime;
            logger.info("reload forbiddenIp");
        }

    }
}
